package com.example.amusic.screen

import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.media3.common.MediaItem
import coil.compose.AsyncImage
import coil.imageLoader
import com.example.amusic.viewmodel.MainIntent
import com.example.amusic.viewmodel.MainViewModel
import com.example.amusic.R
import com.example.amusic.db.SongEntity
import com.example.amusic.ui.theme.colorBlcak55
import com.example.amusic.ui.theme.colorBlcak90
import com.example.amusic.ui.theme.helveticabold
import com.example.amusic.ui.theme.helveticaregular
import com.example.amusic.utils.LocalNavController
import com.example.amusic.utils.getSmallCover
import com.example.amusic.utils.toMediaItem
import com.example.amusic.viewmodel.PlayViewModel

@Composable
fun MusicMain(mainViewModel: MainViewModel, playViewModel: PlayViewModel) {

    LaunchedEffect(key1 = Unit) {
        mainViewModel.dispatch(MainIntent.RequestScan)
    }
    val controller = LocalNavController.current
    //监听扫描结果
    val collectAsState = mainViewModel.mainState.collectAsState()
    val listScan = collectAsState.value.scanList

    val currentSong = mainViewModel.playerController?.currentSong?.observeAsState()

    val playProgress = mainViewModel.playerController?.playProgress?.collectAsState()

    LaunchedEffect(key1 = playProgress) {
        Log.e("TAG_MUSIC", "当前播放的歌曲的进度=${playProgress?.value}")
    }

    LaunchedEffect(key1 = currentSong) {
        currentSong?.let {
            Log.e("TAG_MUSIC", "当前播放的歌曲是${currentSong.value?.mediaMetadata?.title}")
        }
    }

//    val currentSong = remember {
//        mutableStateOf(MyApp.playerController.currentSong.value)
//    }

//    MyApp.playerController.currentSong.observe()

//    var song by remember {
//        mutableStateOf<MediaItem>(null)
//    }
//
//    LaunchedEffect(key1 = currentSong) {
//        song = currentSong.value
//    }

    Scaffold(
        modifier = Modifier
            .fillMaxSize()
            .statusBarsPadding()
            .navigationBarsPadding(),
    ) { padding ->
        if (listScan.isEmpty()) {
            Text(text = "暂无数据")
        } else {
            Box(modifier = Modifier.fillMaxSize()) {
                LazyColumn(modifier = Modifier.padding(padding)) {
                    items(listScan.size) { index ->
                        MusicMainItem(listScan[index]) { data ->
                            mainViewModel.dispatch(MainIntent.OnItemClick(data, index))
                        }
                    }
                }


                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .align(Alignment.BottomCenter)
                        .padding(bottom = 20.dp), horizontalArrangement = Arrangement.SpaceBetween
                ) {
//                    AnimatedVisibility(visible = currentSong.value !== null) {
//                        miniBar(currentSong.value!!)
//                    }
                    Button(onClick = {
                        val songs = mainViewModel.mainState.value.scanList.map { it.toMediaItem() }
                        playViewModel.playAll(songs, songs.first())
//                        mainViewModel.dispatch(MainIntent.PlayAllSongListener)
                    }
                    ) {
                        Text(text = "全部播放")
                    }


                    Button(onClick = {
                        mainViewModel.dispatch(MainIntent.PlayPrevListener)
                    }) {
                        Text(text = "上一首")
                    }

                    Button(onClick = {
                        mainViewModel.dispatch(MainIntent.PlayNextListener)
                    }) {
                        Text(text = "下一首")
                    }
                }
            }

            SideEffect {
                Log.e("TAG-LOG", "MusicMain:  SideEffect")
            }
        }
    }
}


@Composable
fun MusicMainItem(data: SongEntity, onItemClick: (SongEntity) -> Unit) {
    val imgLoader = LocalContext.current.imageLoader
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .padding(top = 16.dp, start = 16.dp, end = 16.dp)
            .clickable {
                onItemClick(data)
            },
        verticalAlignment = Alignment.CenterVertically,
    ) {

        AsyncImage(
            modifier = Modifier
                .size(56.dp)
                .clip(RoundedCornerShape(12.dp)),
            model = data.getLargeCover(),//data.coverUrl,
            contentDescription = "",
            imageLoader = imgLoader,
            contentScale = ContentScale.Crop,
            placeholder = painterResource(id = R.drawable.ic_album),
            error = painterResource(id = R.drawable.ic_album)
        )


        Column(
            modifier = Modifier
                .padding(12.dp)
                .weight(1f)
        ) {
            Text(
                text = data.title,
                style = TextStyle(
                    fontFamily = helveticaregular,
                    color = colorBlcak90,
                    fontSize = 16.sp
                ),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            Spacer(modifier = Modifier.height(2.dp))
            Text(
                text = data.artist,
                style = TextStyle(
                    color = colorBlcak55,
                    fontFamily = helveticabold,
                    fontSize = 12.sp
                ),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
        Icon(imageVector = Icons.Rounded.MoreVert, contentDescription = "more")
    }
}

@Composable
fun miniBar(data: MediaItem) {
//    cover: String, title: String
    val imgLoader = LocalContext.current.imageLoader

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(52.dp)
            .padding(horizontal = 16.dp)
            .clip(RoundedCornerShape(12.dp)),
        verticalAlignment = Alignment.CenterVertically
    ) {
        AsyncImage(
            modifier = Modifier
                .size(52.dp)
                .clip(RoundedCornerShape(12.dp)),
            model = data.getSmallCover(), //cover,//data.coverUrl,
            contentDescription = "",
            imageLoader = imgLoader,
            contentScale = ContentScale.Crop,
            placeholder = painterResource(id = R.drawable.ic_album),
            error = painterResource(id = R.drawable.ic_album)
        )

        Spacer(modifier = Modifier.width(12.dp))
        Text(
            modifier = Modifier.weight(1f),
            text = data.mediaMetadata.title.toString(),
            color = colorBlcak90,
            fontSize = 12.sp
        )
        Spacer(modifier = Modifier.width(12.dp))
        Image(
            modifier = Modifier
                .size(32.dp),
            painter = painterResource(id = R.drawable.icon_play_small),
            contentDescription = "播放/暂停"
        )
        Image(
            modifier = Modifier
                .size(32.dp),
            painter = painterResource(id = R.drawable.icon_play_next),
            contentDescription = "下一首"
        )
        Image(
            modifier = Modifier
                .size(32.dp),
            painter = painterResource(id = R.drawable.icon_play_list),
            contentDescription = "播放列表"
        )
    }
}

@Preview
@Composable
private fun PreviewminiBar() {
//    miniBar()
}


@Preview
@Composable
private fun MusicMainItemPreview() {
//    MusicMainItem(
//        SongBean(
//            coverUrl = Uri.EMPTY,
//            albumName = "专辑名",
//            artistName = "歌手名",
//            duration = 10000,
//            data = "/data/data",
//            dateModified = 0L,
//            songName = "歌曲名",
//            size = 100,
//            id = "",
//            bitrate = 100,
//            samplingRate = 0,
//            lyric = ""
//        )
//    ) {
//
//    }
}